const { app, Menu, BrowserWindow, Tray } = require('electron')
const path = require('path')

let win
let tray

app.whenReady().then(() => {
  createTray()
})

const menus = [
  {
    label: '关于',
    role: 'about',
  },
  { type: 'separator' },
  {
    label: '自定义菜单',
    click: () => {
      console.log('点击自定义')
    },
  },
  {
    label: '子菜单',
    submenu: [
      {
        label: '显示窗口',
        click: () => {
          console.log('点击了二级菜单')
        },
      },
      {
        label: '打开控制台',
        role: 'toggleDevTools',
      },
    ],
  },
  { type: 'separator' },
  {
    label: '退出',
    role: 'quit',
  },
]
function createTray() {
  win = new BrowserWindow({
    width: 600,
    height: 500,
  })
  tray = new Tray(path.join(__dirname, 'phoneTemplate.png'))
  const contextMenu = Menu.buildFromTemplate(menus)
  tray.setContextMenu(contextMenu) // 设置托盘菜单
  tray.setToolTip('点击查看当日天气情况')
  tray.on('click', () => {
    console.log('tray clicked')
  })
  // 能够自动弹出托盘菜单的API
  setTimeout(() => {
    const popUpMenu = Menu.buildFromTemplate([menus[0], menus[menus.length - 1]])
    tray.popUpContextMenu(popUpMenu)
  }, 5000)
}
